package com.tomorrowbbs.service.impl;

import java.util.Date;
import java.util.List;
//import com.newcamping.common.utils.DateUtils;
import com.tomorrowbbs.domain.UserInfo;
import com.tomorrowbbs.domain.config.WebConfig;
import com.tomorrowbbs.domain.constants.Constants;
import com.tomorrowbbs.exception.BusinessException;
import com.tomorrowbbs.mapper.UserInfoMapper;
import com.tomorrowbbs.utils.StringTools;
import org.apache.tomcat.util.bcel.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.tomorrowbbs.mapper.EmailCodeMapper;
import com.tomorrowbbs.domain.EmailCode;
import com.tomorrowbbs.service.IEmailCodeService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

/**
 * 邮箱验证码Service业务层处理
 *
 * @author zjz
 * @date 2024-11-09
 */
@Service
public class EmailCodeServiceImpl implements IEmailCodeService {
    private static final Logger logger = LoggerFactory.getLogger(EmailCodeServiceImpl.class);
    @Autowired
    private EmailCodeMapper emailCodeMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private WebConfig webConfig;
//    @Resource
//    private UserInfoMapper<UserInfo,UserInfoQuery> userInfoMapper;

    /**
     * 查询邮箱验证码
     *
     * @param email 邮箱验证码主键
     * @return 邮箱验证码
     */
    @Override
    public EmailCode selectEmailCodeByEmail(String email) {
        return emailCodeMapper.selectEmailCodeByEmail(email);
    }

    /**
     * 查询邮箱验证码列表
     *
     * @param emailCode 邮箱验证码
     * @return 邮箱验证码
     */
    @Override
    public List<EmailCode> selectEmailCodeList(EmailCode emailCode) {
        return emailCodeMapper.selectEmailCodeList(emailCode);
    }

    /**
     * 新增邮箱验证码
     *
     * @param emailCode 邮箱验证码
     * @return 结果
     */
    @Override
    public int insertEmailCode(EmailCode emailCode) {
//        emailCode.setCreateTime(DateUtils.getNowDate());
        return emailCodeMapper.insertEmailCode(emailCode);
    }

    /**
     * 修改邮箱验证码
     *
     * @param emailCode 邮箱验证码
     * @return 结果
     */
    @Override
    public int updateEmailCode(EmailCode emailCode) {
        return emailCodeMapper.updateEmailCode(emailCode);
    }

    /**
     * 批量删除邮箱验证码
     *
     * @param emails 需要删除的邮箱验证码主键
     * @return 结果
     */
    @Override
    public int deleteEmailCodeByEmails(String[] emails) {
        return emailCodeMapper.deleteEmailCodeByEmails(emails);
    }

    /**
     * 删除邮箱验证码信息
     *
     * @param email 邮箱验证码主键
     * @return 结果
     */
    @Override
    public int deleteEmailCodeByEmail(String email) {
        return emailCodeMapper.deleteEmailCodeByEmail(email);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailCode(String email, Integer type) {

        if (Constants.ZERO == type) {
            //通过email查询用户是否存在
            UserInfo userInfo = userInfoMapper.selectUserInfoByEmail(email);
            System.out.println(userInfo);
            if (userInfo != null) {
                throw new BusinessException("邮箱已存在");
            }
        }
        String code = StringTools.getRandomString(Constants.LENGTH_5);
        //发送邮件
        sendEmailCodeDo(email, code);

        emailCodeMapper.disableEmailCode(email);
        //数据库写入
        EmailCode emailCode = new EmailCode();
        emailCode.setCode(code);
        emailCode.setEmail(email);
        emailCode.setStatus(Constants.ZERO);
        emailCode.setCreateTime(new Date());
        emailCodeMapper.insertEmailCode(emailCode);
    }

    private void sendEmailCodeDo(String toEmail, String code) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //邮件发送人
            helper.setFrom(webConfig.getSendUserName());
            //邮件收件人
            helper.setTo(toEmail);

            helper.setSubject("注册验证码");
            helper.setText("您的验证码为：" + code);
            helper.setSentDate(new Date());
            javaMailSender.send(message);
        } catch (Exception e) {
            logger.error("发送邮件失败", e);
            throw new BusinessException("发送邮件失败");
        }
    }


    public void checkCode(String email, String emailCode) {
        EmailCode dbInfo = emailCodeMapper.selectEmailCodeByEmailAndCode(email, emailCode);
        if (dbInfo == null) {
            throw new BusinessException("邮箱验证码错误");
        }
        if (dbInfo.getStatus() != Constants.ZERO || System.currentTimeMillis() - dbInfo.getCreateTime().getTime() > 1000 * 60 * Constants.LENGTH_15) {
            throw new BusinessException("邮箱验验证码已过期");
        }

        emailCodeMapper.disableEmailCode(email);


    }
}
